package com.ywy.controller;

import com.ywy.entity.Message;
import com.ywy.entity.User;
import com.ywy.service.MessageService;
import com.ywy.utils.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 系统消息Controller
 *
 * @author ywy
 * @date 2022/9/8 14:12
 */
@Controller
@RequestMapping("message")
public class MessageController {
    @Resource
    private MessageService messageService;

    /**
     * 分页查询系统消息
     * @param pageNo
     * @param session
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(@RequestParam(defaultValue = "1") Integer pageNo, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");

        // 分页查询系统消息
        Message message = new Message();
        message.setUser(user);
        List<Message> messageList = messageService.list(message, pageNo, 10);
        Long total = messageService.getTotal(message);

        ModelAndView mav = new ModelAndView();
        mav.addObject("messageList", messageList);
        mav.addObject("pageCode", PageUtil.genPagination("/user/message/list", total, pageNo, 10, ""));
        mav.setViewName("user/message");
        return mav;
    }

    /**
     * 查看系统消息，状态改成已查看
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("see")
    public ModelAndView see(HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        user.setMessageCount(0);
        session.setAttribute("currentUser", user);

        // 修改成已查看状态
        messageService.updateStatus(user.getId());

        Message message = new Message();
        message.setUser(user);
        List<Message> messageList = messageService.list(message, 1, 10);
        Long total = messageService.getTotal(message);

        ModelAndView mav = new ModelAndView();
        mav.addObject("messageList", messageList);
        mav.addObject("pageCode", PageUtil.genPagination("/message/list", total, 1, 10, ""));
        mav.setViewName("user/message");
        return mav;
    }
}
